"use client";

import React, { useState } from "react";
import Typography from "antd/es/typography";
import Tabs from "antd/es/tabs";
import Input from "antd/es/input";
import Button from "antd/es/button";
import Card from "antd/es/card";
import Spin from "antd/es/spin";
import message from "antd/es/message";
import SendOutlined from "@ant-design/icons/SendOutlined";
import ClearOutlined from "@ant-design/icons/ClearOutlined";
import LoadingOutlined from "@ant-design/icons/LoadingOutlined";
import styles from "./test.module.css";
import api from "../../../utils/api/fetch";

const { Title, Paragraph } = Typography;
const { TextArea } = Input;

// 示例提示文本
const placeholders = {
  content: "请输入您想要生成的文章主题或关键词...",
  polish: "请输入需要润色的文案内容...",
  topic: "请输入您感兴趣的领域或目标受众...",
};

export default function TestPage() {
  // 状态管理
  const [activeKey, setActiveKey] = useState("content");
  const [contentInput, setContentInput] = useState("");
  const [contentOutput, setContentOutput] = useState("");
  const [polishInput, setPolishInput] = useState("");
  const [polishOutput, setPolishOutput] = useState("");
  const [topicInput, setTopicInput] = useState("");
  const [topicOutput, setTopicOutput] = useState("");
  const [loading, setLoading] = useState(false);

  // 处理标签页切换
  const handleTabChange = (key: string) => {
    setActiveKey(key);
  };

  // 生成随机openId
  const generateRandomOpenId = () => {
    return (
      Math.random().toString(36).substring(2, 15) +
      Math.random().toString(36).substring(2, 15)
    );
  };

  // 处理生成请求
  const handleGenerate = async (type: string) => {
    let input = "";
    switch (type) {
      case "content":
        input = contentInput;
        break;
      case "polish":
        input = polishInput;
        break;
      case "topic":
        input = topicInput;
        break;
      default:
        break;
    }

    if (!input.trim()) {
      message.warning("请先输入内容");
      return;
    }

    setLoading(true);

    try {
      let output = "";

      // 根据类型调用不同的API
      if (type === "content") {
        // 生成随机openId
        const openId = generateRandomOpenId();

        // 调用/ai/writing接口
        const response = await api.post("/ai/writing", {
          value: input,
          openId: openId,
        });

        // 检查API响应
        if (response.success) {
          output = response.data;
        } else {
          throw new Error(response.message || "生成文案失败");
        }
      } else if (type === "polish") {
        // 这里保留原来的模拟逻辑，后续可以替换为实际API调用
        output = input
          .replace(/([。！？])\s*/g, "$1\n\n")
          .replace(/([，；：])\s*/g, "$1 ")
          .replace(/\b([a-z])/g, (_, c) => c.toUpperCase())
          .replace(/很/g, "非常")
          .replace(/好/g, "优秀")
          .replace(/大/g, "宏大")
          .replace(/小/g, "精致")
          .replace(/快/g, "迅速")
          .replace(/慢/g, "从容");
        output = `【润色后的文案】\n\n${output}\n\n【润色说明】\n\n1. 优化了标点符号的使用和段落结构\n2. 提升了用词的精准性和表达的丰富度\n3. 增强了文案的专业感和吸引力\n4. 保持了原文的核心信息和主要观点`;
      } else if (type === "topic") {
        // 这里保留原来的模拟逻辑，后续可以替换为实际API调用
        const topics = [
          `${input}领域的最新技术趋势分析`,
          `如何在${input}行业中脱颖而出：专家建议`,
          `${input}的未来发展：机遇与挑战`,
          `${input}领域的10个创新案例分析`,
          `${input}入门指南：从零开始的完整路线图`,
          `${input}与人工智能的结合：新的可能性`,
          `${input}行业的商业模式创新`,
          `${input}领域的用户体验设计原则`,
          `${input}的社会影响与伦理考量`,
          `${input}领域的国际比较研究`,
        ];

        output = `## 为您推荐的"${input}"相关选题：\n\n${topics
          .map(
            (topic, index) =>
              `### ${index + 1}. ${topic}\n选题说明：这个主题关注${input}的${
                [
                  "核心问题",
                  "发展趋势",
                  "实践应用",
                  "创新方向",
                  "基础知识",
                  "技术融合",
                  "商业价值",
                  "用户需求",
                  "社会责任",
                  "全球视野",
                ][index]
              }，适合${
                [
                  "行业专家",
                  "求职者",
                  "投资者",
                  "创新者",
                  "初学者",
                  "技术爱好者",
                  "企业管理者",
                  "设计师",
                  "政策制定者",
                  "研究人员",
                ][index]
              }阅读。\n`
          )
          .join("\n")}`;
      }

      // 更新对应的输出
      switch (type) {
        case "content":
          setContentOutput(output);
          break;
        case "polish":
          setPolishOutput(output);
          break;
        case "topic":
          setTopicOutput(output);
          break;
        default:
          break;
      }

      message.success(
        `${
          type === "content" ? "文案" : type === "polish" ? "润色文案" : "选题"
        }生成成功！`
      );
    } catch (error) {
      message.error("生成失败，请稍后重试");
      console.error("生成错误:", error);
    } finally {
      setLoading(false);
    }
  };

  // 清空输入和输出
  const handleClear = (type: string) => {
    switch (type) {
      case "content":
        setContentInput("");
        setContentOutput("");
        break;
      case "polish":
        setPolishInput("");
        setPolishOutput("");
        break;
      case "topic":
        setTopicInput("");
        setTopicOutput("");
        break;
      default:
        break;
    }
    message.info(
      `已清空${
        type === "content" ? "文案" : type === "polish" ? "润色文案" : "选题"
      }输入和输出`
    );
  };

  // 渲染文本区域
  const renderTextAreas = (type: string) => {
    let input = "";
    let output = "";
    let setInput: (value: string) => void;
    let placeholder = "";

    switch (type) {
      case "content":
        input = contentInput;
        output = contentOutput;
        setInput = setContentInput;
        placeholder = placeholders.content;
        break;
      case "polish":
        input = polishInput;
        output = polishOutput;
        setInput = setPolishInput;
        placeholder = placeholders.polish;
        break;
      case "topic":
        input = topicInput;
        output = topicOutput;
        setInput = setTopicInput;
        placeholder = placeholders.topic;
        break;
      default:
        return null;
    }

    return (
      <div className={styles.textAreaContainer}>
        <div className={styles.textAreaWrapper}>
          <div className={styles.textAreaLabel}>输入：</div>
          <TextArea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            className={styles.inputTextArea}
            placeholder={placeholder}
            autoSize={{ minRows: 12, maxRows: 20 }}
          />
        </div>

        <div className={styles.textAreaWrapper}>
          <div className={styles.textAreaLabel}>输出：</div>
          {loading ? (
            <div className={styles.loadingContainer}>
              <div>
                <Spin
                  indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
                />
                <div
                  style={{ marginTop: 16, color: "rgba(255, 255, 255, 0.65)" }}
                >
                  正在生成中...
                </div>
              </div>
            </div>
          ) : (
            <TextArea
              value={output}
              readOnly
              className={styles.outputTextArea}
              placeholder="输出结果将显示在这里..."
              autoSize={{ minRows: 12, maxRows: 20 }}
            />
          )}
        </div>
      </div>
    );
  };

  return (
    <div className={styles.container}>
      <Title level={2} style={{ color: "white" }}>
        测试
      </Title>

      <Card className={styles.card}>
        <Paragraph className={styles.description}>
          在这里，您可以测试不同类型的AI生成功能。选择一个测试类型，输入相关内容，然后点击"生成"按钮查看结果。
        </Paragraph>

        <Tabs
          activeKey={activeKey}
          onChange={handleTabChange}
          className={styles.tabsContainer}
          type="card"
          items={[
            {
              key: "content",
              label: "文案",
              children: (
                <div className={styles.tabContent}>
                  {renderTextAreas("content")}
                  <div className={styles.actionButtons}>
                    <Button
                      icon={<ClearOutlined />}
                      onClick={() => handleClear("content")}
                    >
                      清空
                    </Button>
                    <Button
                      type="primary"
                      icon={<SendOutlined />}
                      onClick={() => handleGenerate("content")}
                      loading={loading && activeKey === "content"}
                    >
                      生成
                    </Button>
                  </div>
                </div>
              ),
            },
            {
              key: "polish",
              label: "润色文案",
              children: (
                <div className={styles.tabContent}>
                  {renderTextAreas("polish")}
                  <div className={styles.actionButtons}>
                    <Button
                      icon={<ClearOutlined />}
                      onClick={() => handleClear("polish")}
                    >
                      清空
                    </Button>
                    <Button
                      type="primary"
                      icon={<SendOutlined />}
                      onClick={() => handleGenerate("polish")}
                      loading={loading && activeKey === "polish"}
                    >
                      生成
                    </Button>
                  </div>
                </div>
              ),
            },
            {
              key: "topic",
              label: "选题",
              children: (
                <div className={styles.tabContent}>
                  {renderTextAreas("topic")}
                  <div className={styles.actionButtons}>
                    <Button
                      icon={<ClearOutlined />}
                      onClick={() => handleClear("topic")}
                    >
                      清空
                    </Button>
                    <Button
                      type="primary"
                      icon={<SendOutlined />}
                      onClick={() => handleGenerate("topic")}
                      loading={loading && activeKey === "topic"}
                    >
                      生成
                    </Button>
                  </div>
                </div>
              ),
            },
          ]}
        />
      </Card>
    </div>
  );
}
